/**
 * 统计相关Mock数据
 */

import { generateId, randomNumber, randomFloat, randomChoice, randomDate, formatDate } from '../utils'

// 生成模拟统计数据
function generateStatsData() {
  const now = new Date()
  const data = {
    // 习惯统计数据
    habits: generateHabitsStats(now),
    // 财务统计数据
    finance: generateFinanceStats(now),
    // 时间统计数据
    time: generateTimeStats(now),
    // 待办统计数据
    todos: generateTodosStats(now),
    // 综合统计数据
    overview: {}
  }
  
  // 生成综合统计
  data.overview = generateOverviewStats(data)
  
  return data
}

// 生成习惯统计数据
function generateHabitsStats(now) {
  const habits = []
  const categories = ['健康', '学习', '工作', '生活', '运动']
  
  // 生成30天的习惯数据
  for (let i = 29; i >= 0; i--) {
    const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
    const dateStr = formatDate(date, 'YYYY-MM-DD')
    
    habits.push({
      date: dateStr,
      totalHabits: randomNumber(5, 12),
      completedHabits: randomNumber(3, 8),
      completionRate: randomNumber(60, 95),
      streakDays: randomNumber(1, 15),
      categories: categories.map(category => ({
        name: category,
        total: randomNumber(1, 3),
        completed: randomNumber(0, 3)
      }))
    })
  }
  
  return {
    daily: habits,
    weekly: generateWeeklyHabitsStats(habits),
    monthly: generateMonthlyHabitsStats(habits),
    trends: generateHabitsTrends(habits)
  }
}

// 生成财务统计数据
function generateFinanceStats(now) {
  const transactions = []
  const categories = {
    income: ['工资', '奖金', '投资收益', '其他收入'],
    expense: ['餐饮', '交通', '购物', '娱乐', '医疗', '教育', '房租', '水电费']
  }
  
  // 生成30天的财务数据
  for (let i = 29; i >= 0; i--) {
    const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
    const dateStr = formatDate(date, 'YYYY-MM-DD')
    
    const income = randomFloat(0, 2000, 2)
    const expense = randomFloat(50, 500, 2)
    
    transactions.push({
      date: dateStr,
      income,
      expense,
      balance: income - expense,
      incomeCategories: categories.income.map(category => ({
        name: category,
        amount: randomFloat(0, income / 2, 2)
      })),
      expenseCategories: categories.expense.map(category => ({
        name: category,
        amount: randomFloat(0, expense / 4, 2)
      }))
    })
  }
  
  return {
    daily: transactions,
    weekly: generateWeeklyFinanceStats(transactions),
    monthly: generateMonthlyFinanceStats(transactions),
    trends: generateFinanceTrends(transactions),
    budgets: generateBudgetStats()
  }
}

// 生成时间统计数据
function generateTimeStats(now) {
  const timeRecords = []
  const activities = ['工作', '学习', '运动', '娱乐', '社交', '休息']
  
  // 生成30天的时间数据
  for (let i = 29; i >= 0; i--) {
    const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
    const dateStr = formatDate(date, 'YYYY-MM-DD')
    
    const totalTime = randomNumber(480, 720) // 8-12小时
    
    timeRecords.push({
      date: dateStr,
      totalTime,
      productivity: randomNumber(60, 95),
      focusTime: randomNumber(240, 480),
      breakTime: randomNumber(60, 120),
      activities: activities.map(activity => ({
        name: activity,
        duration: randomNumber(30, 180),
        sessions: randomNumber(1, 5)
      }))
    })
  }
  
  return {
    daily: timeRecords,
    weekly: generateWeeklyTimeStats(timeRecords),
    monthly: generateMonthlyTimeStats(timeRecords),
    trends: generateTimeTrends(timeRecords)
  }
}

// 生成待办统计数据
function generateTodosStats(now) {
  const todos = []
  const priorities = ['high', 'medium', 'low']
  
  // 生成30天的待办数据
  for (let i = 29; i >= 0; i--) {
    const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
    const dateStr = formatDate(date, 'YYYY-MM-DD')
    
    const totalTodos = randomNumber(5, 15)
    const completedTodos = randomNumber(3, totalTodos)
    
    todos.push({
      date: dateStr,
      totalTodos,
      completedTodos,
      pendingTodos: totalTodos - completedTodos,
      completionRate: Math.round((completedTodos / totalTodos) * 100),
      overdueTodos: randomNumber(0, 3),
      priorities: priorities.map(priority => ({
        name: priority,
        total: randomNumber(1, 5),
        completed: randomNumber(0, 3)
      }))
    })
  }
  
  return {
    daily: todos,
    weekly: generateWeeklyTodosStats(todos),
    monthly: generateMonthlyTodosStats(todos),
    trends: generateTodosTrends(todos)
  }
}

// 生成综合统计数据
function generateOverviewStats(data) {
  const today = data.habits.daily[data.habits.daily.length - 1]
  const thisWeek = data.habits.weekly[data.habits.weekly.length - 1]
  const thisMonth = data.habits.monthly[data.habits.monthly.length - 1]
  
  return {
    today: {
      habitsCompletion: today.completionRate,
      todosCompletion: data.todos.daily[data.todos.daily.length - 1].completionRate,
      timeProductivity: data.time.daily[data.time.daily.length - 1].productivity,
      financeBalance: data.finance.daily[data.finance.daily.length - 1].balance,
      score: randomNumber(75, 95)
    },
    week: {
      habitsCompletion: thisWeek.avgCompletionRate,
      todosCompletion: data.todos.weekly[data.todos.weekly.length - 1].avgCompletionRate,
      timeProductivity: data.time.weekly[data.time.weekly.length - 1].avgProductivity,
      financeBalance: data.finance.weekly[data.finance.weekly.length - 1].totalBalance,
      score: randomNumber(70, 90)
    },
    month: {
      habitsCompletion: thisMonth.avgCompletionRate,
      todosCompletion: data.todos.monthly[data.todos.monthly.length - 1].avgCompletionRate,
      timeProductivity: data.time.monthly[data.time.monthly.length - 1].avgProductivity,
      financeBalance: data.finance.monthly[data.finance.monthly.length - 1].totalBalance,
      score: randomNumber(65, 85)
    },
    trends: {
      habits: data.habits.trends,
      finance: data.finance.trends,
      time: data.time.trends,
      todos: data.todos.trends
    }
  }
}

// 生成周统计数据
function generateWeeklyHabitsStats(dailyData) {
  const weeks = []
  for (let i = 0; i < dailyData.length; i += 7) {
    const weekData = dailyData.slice(i, i + 7)
    if (weekData.length === 7) {
      const totalHabits = weekData.reduce((sum, day) => sum + day.totalHabits, 0)
      const completedHabits = weekData.reduce((sum, day) => sum + day.completedHabits, 0)
      
      weeks.push({
        weekStart: weekData[0].date,
        weekEnd: weekData[6].date,
        totalHabits,
        completedHabits,
        avgCompletionRate: Math.round((completedHabits / totalHabits) * 100),
        bestDay: weekData.reduce((best, day) => 
          day.completionRate > best.completionRate ? day : best
        ),
        worstDay: weekData.reduce((worst, day) => 
          day.completionRate < worst.completionRate ? day : worst
        )
      })
    }
  }
  return weeks
}

// 生成月统计数据
function generateMonthlyHabitsStats(dailyData) {
  const totalHabits = dailyData.reduce((sum, day) => sum + day.totalHabits, 0)
  const completedHabits = dailyData.reduce((sum, day) => sum + day.completedHabits, 0)
  
  return [{
    month: formatDate(new Date(), 'YYYY-MM'),
    totalHabits,
    completedHabits,
    avgCompletionRate: Math.round((completedHabits / totalHabits) * 100),
    bestDay: dailyData.reduce((best, day) => 
      day.completionRate > best.completionRate ? day : best
    ),
    worstDay: dailyData.reduce((worst, day) => 
      day.completionRate < worst.completionRate ? day : worst
    ),
    totalDays: dailyData.length,
    perfectDays: dailyData.filter(day => day.completionRate === 100).length
  }]
}

// 生成趋势数据
function generateHabitsTrends(dailyData) {
  const recent7Days = dailyData.slice(-7)
  const previous7Days = dailyData.slice(-14, -7)
  
  const recentAvg = recent7Days.reduce((sum, day) => sum + day.completionRate, 0) / 7
  const previousAvg = previous7Days.reduce((sum, day) => sum + day.completionRate, 0) / 7
  
  return {
    direction: recentAvg > previousAvg ? 'up' : recentAvg < previousAvg ? 'down' : 'stable',
    change: Math.abs(recentAvg - previousAvg),
    changePercent: previousAvg > 0 ? Math.round(((recentAvg - previousAvg) / previousAvg) * 100) : 0
  }
}

// 生成财务周统计
function generateWeeklyFinanceStats(dailyData) {
  const weeks = []
  for (let i = 0; i < dailyData.length; i += 7) {
    const weekData = dailyData.slice(i, i + 7)
    if (weekData.length === 7) {
      const totalIncome = weekData.reduce((sum, day) => sum + day.income, 0)
      const totalExpense = weekData.reduce((sum, day) => sum + day.expense, 0)
      
      weeks.push({
        weekStart: weekData[0].date,
        weekEnd: weekData[6].date,
        totalIncome: parseFloat(totalIncome.toFixed(2)),
        totalExpense: parseFloat(totalExpense.toFixed(2)),
        totalBalance: parseFloat((totalIncome - totalExpense).toFixed(2)),
        avgDailyExpense: parseFloat((totalExpense / 7).toFixed(2))
      })
    }
  }
  return weeks
}

// 生成财务月统计
function generateMonthlyFinanceStats(dailyData) {
  const totalIncome = dailyData.reduce((sum, day) => sum + day.income, 0)
  const totalExpense = dailyData.reduce((sum, day) => sum + day.expense, 0)
  
  return [{
    month: formatDate(new Date(), 'YYYY-MM'),
    totalIncome: parseFloat(totalIncome.toFixed(2)),
    totalExpense: parseFloat(totalExpense.toFixed(2)),
    totalBalance: parseFloat((totalIncome - totalExpense).toFixed(2)),
    avgDailyIncome: parseFloat((totalIncome / dailyData.length).toFixed(2)),
    avgDailyExpense: parseFloat((totalExpense / dailyData.length).toFixed(2)),
    savingsRate: totalIncome > 0 ? Math.round(((totalIncome - totalExpense) / totalIncome) * 100) : 0
  }]
}

// 生成财务趋势
function generateFinanceTrends(dailyData) {
  const recent7Days = dailyData.slice(-7)
  const previous7Days = dailyData.slice(-14, -7)
  
  const recentExpense = recent7Days.reduce((sum, day) => sum + day.expense, 0)
  const previousExpense = previous7Days.reduce((sum, day) => sum + day.expense, 0)
  
  return {
    expense: {
      direction: recentExpense > previousExpense ? 'up' : recentExpense < previousExpense ? 'down' : 'stable',
      change: Math.abs(recentExpense - previousExpense),
      changePercent: previousExpense > 0 ? Math.round(((recentExpense - previousExpense) / previousExpense) * 100) : 0
    }
  }
}

// 生成预算统计
function generateBudgetStats() {
  const categories = ['餐饮', '交通', '购物', '娱乐', '医疗', '教育']
  
  return categories.map(category => {
    const budget = randomFloat(500, 2000, 2)
    const spent = randomFloat(200, budget * 1.2, 2)
    
    return {
      category,
      budget,
      spent,
      remaining: Math.max(0, budget - spent),
      percentage: Math.round((spent / budget) * 100),
      status: spent > budget ? 'over' : spent > budget * 0.8 ? 'warning' : 'normal'
    }
  })
}

// 生成时间周统计
function generateWeeklyTimeStats(dailyData) {
  const weeks = []
  for (let i = 0; i < dailyData.length; i += 7) {
    const weekData = dailyData.slice(i, i + 7)
    if (weekData.length === 7) {
      const totalTime = weekData.reduce((sum, day) => sum + day.totalTime, 0)
      const avgProductivity = weekData.reduce((sum, day) => sum + day.productivity, 0) / 7
      
      weeks.push({
        weekStart: weekData[0].date,
        weekEnd: weekData[6].date,
        totalTime,
        avgProductivity: Math.round(avgProductivity),
        avgDailyTime: Math.round(totalTime / 7)
      })
    }
  }
  return weeks
}

// 生成时间月统计
function generateMonthlyTimeStats(dailyData) {
  const totalTime = dailyData.reduce((sum, day) => sum + day.totalTime, 0)
  const avgProductivity = dailyData.reduce((sum, day) => sum + day.productivity, 0) / dailyData.length
  
  return [{
    month: formatDate(new Date(), 'YYYY-MM'),
    totalTime,
    avgProductivity: Math.round(avgProductivity),
    avgDailyTime: Math.round(totalTime / dailyData.length),
    totalDays: dailyData.length
  }]
}

// 生成时间趋势
function generateTimeTrends(dailyData) {
  const recent7Days = dailyData.slice(-7)
  const previous7Days = dailyData.slice(-14, -7)
  
  const recentProductivity = recent7Days.reduce((sum, day) => sum + day.productivity, 0) / 7
  const previousProductivity = previous7Days.reduce((sum, day) => sum + day.productivity, 0) / 7
  
  return {
    productivity: {
      direction: recentProductivity > previousProductivity ? 'up' : recentProductivity < previousProductivity ? 'down' : 'stable',
      change: Math.abs(recentProductivity - previousProductivity),
      changePercent: previousProductivity > 0 ? Math.round(((recentProductivity - previousProductivity) / previousProductivity) * 100) : 0
    }
  }
}

// 生成待办周统计
function generateWeeklyTodosStats(dailyData) {
  const weeks = []
  for (let i = 0; i < dailyData.length; i += 7) {
    const weekData = dailyData.slice(i, i + 7)
    if (weekData.length === 7) {
      const totalTodos = weekData.reduce((sum, day) => sum + day.totalTodos, 0)
      const completedTodos = weekData.reduce((sum, day) => sum + day.completedTodos, 0)
      
      weeks.push({
        weekStart: weekData[0].date,
        weekEnd: weekData[6].date,
        totalTodos,
        completedTodos,
        avgCompletionRate: totalTodos > 0 ? Math.round((completedTodos / totalTodos) * 100) : 0
      })
    }
  }
  return weeks
}

// 生成待办月统计
function generateMonthlyTodosStats(dailyData) {
  const totalTodos = dailyData.reduce((sum, day) => sum + day.totalTodos, 0)
  const completedTodos = dailyData.reduce((sum, day) => sum + day.completedTodos, 0)
  
  return [{
    month: formatDate(new Date(), 'YYYY-MM'),
    totalTodos,
    completedTodos,
    avgCompletionRate: totalTodos > 0 ? Math.round((completedTodos / totalTodos) * 100) : 0,
    totalDays: dailyData.length
  }]
}

// 生成待办趋势
function generateTodosTrends(dailyData) {
  const recent7Days = dailyData.slice(-7)
  const previous7Days = dailyData.slice(-14, -7)
  
  const recentCompletion = recent7Days.reduce((sum, day) => sum + day.completionRate, 0) / 7
  const previousCompletion = previous7Days.reduce((sum, day) => sum + day.completionRate, 0) / 7
  
  return {
    completion: {
      direction: recentCompletion > previousCompletion ? 'up' : recentCompletion < previousCompletion ? 'down' : 'stable',
      change: Math.abs(recentCompletion - previousCompletion),
      changePercent: previousCompletion > 0 ? Math.round(((recentCompletion - previousCompletion) / previousCompletion) * 100) : 0
    }
  }
}

// 生成统计数据
const mockStatsData = generateStatsData()

export default {
  // 获取综合统计
  'GET /stats/overview': async (params = {}) => {
    const { period = 'today' } = params
    
    if (!['today', 'week', 'month'].includes(period)) {
      throw new Error(JSON.stringify({ code: 1001, message: '无效的时间周期' }))
    }
    
    return mockStatsData.overview[period]
  },
  
  // 获取习惯统计
  'GET /stats/habits': async (params = {}) => {
    const { period = 'daily', startDate, endDate } = params
    
    if (!['daily', 'weekly', 'monthly'].includes(period)) {
      throw new Error(JSON.stringify({ code: 1001, message: '无效的时间周期' }))
    }
    
    let data = mockStatsData.habits[period]
    
    // 日期筛选
    if (startDate || endDate) {
      data = data.filter(item => {
        const itemDate = item.date || item.weekStart || item.month
        if (startDate && itemDate < startDate) return false
        if (endDate && itemDate > endDate) return false
        return true
      })
    }
    
    return {
      period,
      data,
      trends: mockStatsData.habits.trends
    }
  },
  
  // 获取财务统计
  'GET /stats/finance': async (params = {}) => {
    const { period = 'daily', startDate, endDate } = params
    
    if (!['daily', 'weekly', 'monthly'].includes(period)) {
      throw new Error(JSON.stringify({ code: 1001, message: '无效的时间周期' }))
    }
    
    let data = mockStatsData.finance[period]
    
    // 日期筛选
    if (startDate || endDate) {
      data = data.filter(item => {
        const itemDate = item.date || item.weekStart || item.month
        if (startDate && itemDate < startDate) return false
        if (endDate && itemDate > endDate) return false
        return true
      })
    }
    
    return {
      period,
      data,
      trends: mockStatsData.finance.trends,
      budgets: mockStatsData.finance.budgets
    }
  },
  
  // 获取时间统计
  'GET /stats/time': async (params = {}) => {
    const { period = 'daily', startDate, endDate } = params
    
    if (!['daily', 'weekly', 'monthly'].includes(period)) {
      throw new Error(JSON.stringify({ code: 1001, message: '无效的时间周期' }))
    }
    
    let data = mockStatsData.time[period]
    
    // 日期筛选
    if (startDate || endDate) {
      data = data.filter(item => {
        const itemDate = item.date || item.weekStart || item.month
        if (startDate && itemDate < startDate) return false
        if (endDate && itemDate > endDate) return false
        return true
      })
    }
    
    return {
      period,
      data,
      trends: mockStatsData.time.trends
    }
  },
  
  // 获取待办统计
  'GET /stats/todos': async (params = {}) => {
    const { period = 'daily', startDate, endDate } = params
    
    if (!['daily', 'weekly', 'monthly'].includes(period)) {
      throw new Error(JSON.stringify({ code: 1001, message: '无效的时间周期' }))
    }
    
    let data = mockStatsData.todos[period]
    
    // 日期筛选
    if (startDate || endDate) {
      data = data.filter(item => {
        const itemDate = item.date || item.weekStart || item.month
        if (startDate && itemDate < startDate) return false
        if (endDate && itemDate > endDate) return false
        return true
      })
    }
    
    return {
      period,
      data,
      trends: mockStatsData.todos.trends
    }
  },
  
  // 获取趋势分析
  'GET /stats/trends': async (params = {}) => {
    const { module } = params
    
    if (module && !['habits', 'finance', 'time', 'todos'].includes(module)) {
      throw new Error(JSON.stringify({ code: 1001, message: '无效的模块' }))
    }
    
    if (module) {
      return {
        module,
        trends: mockStatsData.overview.trends[module]
      }
    }
    
    return {
      trends: mockStatsData.overview.trends
    }
  },
  
  // 获取对比分析
  'GET /stats/comparison': async (params = {}) => {
    const { period1, period2, module = 'overview' } = params
    
    // 简化的对比分析，实际应用中需要更复杂的逻辑
    const comparison = {
      period1: period1 || formatDate(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), 'YYYY-MM-DD'),
      period2: period2 || formatDate(new Date(), 'YYYY-MM-DD'),
      module,
      metrics: {
        improvement: randomNumber(5, 25),
        decline: randomNumber(0, 10),
        stable: randomNumber(60, 80)
      },
      details: {
        habits: {
          completionRate: {
            period1: randomNumber(70, 85),
            period2: randomNumber(75, 90),
            change: randomNumber(-5, 15)
          }
        },
        finance: {
          savings: {
            period1: randomFloat(500, 1500, 2),
            period2: randomFloat(600, 1800, 2),
            change: randomFloat(-200, 300, 2)
          }
        },
        time: {
          productivity: {
            period1: randomNumber(65, 80),
            period2: randomNumber(70, 85),
            change: randomNumber(-5, 15)
          }
        },
        todos: {
          completionRate: {
            period1: randomNumber(60, 80),
            period2: randomNumber(65, 85),
            change: randomNumber(-5, 15)
          }
        }
      }
    }
    
    return comparison
  },
  
  // 获取排行榜
  'GET /stats/leaderboard': async (params = {}) => {
    const { type = 'habits', period = 'week' } = params
    
    const users = []
    for (let i = 0; i < 10; i++) {
      users.push({
        id: generateId(),
        username: `用户${i + 1}`,
        avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${i}`,
        score: randomNumber(60, 100),
        rank: i + 1,
        metrics: {
          habits: randomNumber(70, 95),
          finance: randomFloat(1000, 5000, 2),
          time: randomNumber(400, 600),
          todos: randomNumber(80, 100)
        }
      })
    }
    
    // 按分数排序
    users.sort((a, b) => b.score - a.score)
    users.forEach((user, index) => {
      user.rank = index + 1
    })
    
    return {
      type,
      period,
      users,
      currentUser: {
        rank: randomNumber(15, 50),
        score: randomNumber(70, 85)
      }
    }
  }
}